<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogroleVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',index1==0?'topbottom':'','center1']"
            >
              <el-col :span="5">
                <el-tag closable @close="closeTag(item1.id,scope.row)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2==0?'':'topbottom','center1']"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="closeTag(item2.id,scope.row)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      v-for="(item3,index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="closeTag(item3.id,scope.row)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-search">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="open(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹出对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogroleVisible" width="50%">
      <!-- 添加表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addroleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" :clearable="true"></el-input>
        </el-form-item>
      </el-form>
      <!-- 确认取消 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogroleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        show-checkbox
        node-key="id"
        default-expand-all
        ref="treeRef"
        :props="treeprops"
        :default-checked-keys="arr"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dialogroleVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      addFormRules: {
        roleName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ]
      },
      arr: [],
      roleslist: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      treeprops: {
        children: "children",
        label: "authName"
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //删除
    open(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getRolesList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    addrole() {
      this.$refs.addroleFormRef.validate(async valid => {
        if (!valid) return this.$message.error("请输入正确信息");
        // 提交表单
        const { data: result } = await this.$http.post("roles", this.addForm);
        console.log(result);

        if (result.meta.status !== 201) {
          this.$message.error(result.meta.msg);
          return (this.dialogroleVisible = false);
        } else {
          this.$message.success(result.meta.msg);
          this.dialogroleVisible = false;
          this.getRolesList();
        }
      });
    },
    // 点击为角色分配权限
    async allotRights() {
      console.log(this.$refs.treeRef.getCheckedKeys());

      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];

      const idStr = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败！");
      }

      this.$message.success("分配权限成功！");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.arr = [];
      this.roleId = role.id;
      // 获取所有权限的数据
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败！");
      }

      // 把获取到的权限数据保存到 data 中
      this.rightslist = res.data;

      // 递归获取三级节点的Id

      this.getLeafKeys(role, this.arr);

      this.setRightDialogVisible = true;
    },
    getLeafKeys(node, arr) {
      console.log(arr);

      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    async closeTag(id, role) {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => {
        return err;
      });
      if (confirm !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${id}`
        );
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        } else {
          this.$message.success(res.meta.msg);
          role.children = res.data;
        }
      }
    },
    // 获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }

      this.roleslist = res.data;

      console.log(this.roleslist);
    }
  }
};
</script>
<style lang="less" scoped>
.topbottom {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.center1 {
  display: flex;
  align-items: center;
}
</style>